//
//  AppDelegate.m
//  ErWa
//
//  Created by 王阳阳 on 16/3/9.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "AppDelegate.h"
#import "NewNestHeader.h"
#import "BCDateBase.h"
#import <RongIMKit/RongIMKit.h>
#import "JPUSHService.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import "FirstView.h"
@interface AppDelegate ()<UIScrollViewDelegate>
@property (nonatomic, retain)UIScrollView *scrollView;
@end

@implementation AppDelegate

-(instancetype)init
{
    self = [super init];
    if (self) {
        NSLog(@"SK == %s",__FUNCTION__);
        
        
    }
    return self;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [NSThread sleepForTimeInterval:2.0];

  

    // 创建 添加
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] ;
    self.window.backgroundColor = [UIColor whiteColor];
    // 设置根视图
    BaseTabBarViewController *baseTabBar = [[BaseTabBarViewController alloc]init];
    self.window.rootViewController = baseTabBar;
    
    
    
    //设置提醒
    NSDate* now=[NSDate date];
    NSArray* notes=[[BCDateBase defaultBase] allNotesOnDate:now];
    [self sendLocalNotificationsWithNotes:notes];
    NSLog(@"notesCount=%ld,notesArray=%@",notes.count,notes);
    [self.window makeKeyAndVisible];

    
    
    /**<  即时通讯 */
    [[RCIM sharedRCIM] initWithAppKey:@"pgyu6atqyl3ru"];
    
    [[RCIM sharedRCIM] connectWithToken:@"8XpbFa9gnSr3m5dNlbGuM4wA5oi4Z4MHxoKtrrmTvb2VqQPCgVb2AohzGj4hU/9eBzVHvRFdP16GkdvKAUx7nF3ijnEy8tr9" success:^(NSString *userId) {
        
    } error:^(RCConnectErrorCode status) {
        
    } tokenIncorrect:^{
        
    }];
    
    //远程推送
    //Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
    }else{
        // categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert) categories:nil];
        
    }
    // Required
    //如需兼容旧版本的方式，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化和同时使用pushConfig.plist文件声明appKey等配置内容。
    [JPUSHService setupWithOption:launchOptions appKey:@"1514f2780bd7f57be6ba8c6b" channel:nil apsForProduction:YES];
    

//    //引导页
    NSMutableArray *a = [@[@"Y1.png",@"Y2.png",@"Y3.png"]mutableCopy];
//
//    
//    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"firstLaunch"]== NO)
//    {
        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"firstLaunch"];
        FirstView *f = [[FirstView alloc]initWithFrame:CGRectMake(0, 0, 375, 667) arr:a];
        [self.window addSubview:f];
//    }
    
    
    
    return YES;
    
    
}

#pragma mark - 重写handleopenURL

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
   
    return  [TencentOAuth HandleOpenURL:url];
}
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    
    return  [TencentOAuth HandleOpenURL:url];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)sendLocalNotificationsWithNotes:(NSArray*)notes
{
    if (notes==nil||notes.count==0) {
        return;
        NSAssert(0, @"notes Array should not be empty!");
    }
    
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    
    for (NSInteger i=0;i<notes.count ;i++ ) {
        NSDictionary* note=[notes objectAtIndex:i];
        NSDate* date=[note valueForKey:@"date"];
//        BCAlertMode mode=(BCAlertMode)[[note valueForKey:@"AlertMode"] integerValue];
        UILocalNotification* notification=[[UILocalNotification alloc]init];
        notification.soundName=UILocalNotificationDefaultSoundName;
        notification.hasAction=YES;
        notification.alertAction=@"查看";
        notification.alertBody=@"您有一项新的日程需要完成";
        notification.applicationIconBadgeNumber=1;
        NSLog(@">>>>>>>>>>>date=%@",date);
        notification.fireDate=date;
        notification.timeZone=[NSTimeZone timeZoneForSecondsFromGMT:0*3600];
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    }
    NSLog(@"localNotification is schedualed! count=%ld，notifications=%@",[[UIApplication sharedApplication] scheduledLocalNotifications].count,[[UIApplication sharedApplication]scheduledLocalNotifications]);
}


// 设备注册远程通知
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    
    // Required
    [JPUSHService registerDeviceToken:deviceToken];
    NSLog(@"注册<<<<<%@",deviceToken);
}
// 用户收到远程通知
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"用户收到>>>>%@",userInfo);
    
}
// 完成远程通知处理程序
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    
    // ios7 以后需要支持的
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
    
    
}
// 注册远程通知后失败结果
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error:%@",error);
    
}
@end
